local prefix = 'generator:id:';
local partitionCount = 1024;
local step = 2; -- 一跳步长
local startStep = 0; -- 起始值

-- 第一个KEY是model，或者是table name
local tag = KEYS[1];
local partition
-- 第二个KEY是分区，若未传入则设置为0，若超出限定大小4096，归0
if KEYS[2] == nil then
    partition = 0;
else
    partition = tonumber(KEYS[2]) % partitionCount;
end
-- 第三个KEY是步长，可不填
if KEYS[3] ~= nil then
    step = tonumber(KEYS[3]);
end


-- 拼接KEY，exp > generator:id:user:0
local milliSecondKey = prefix .. tag ..':' .. partition;

local count;
repeat
    count = tonumber(redis.call('INCRBY', milliSecondKey, step));
    if count >= (4096 - step) then
        count = step;
        redis.call('SET', milliSecondKey, count);
    end;
until count < (4096 - step)

if count == step then
    redis.call('PEXPIRE', milliSecondKey, 1);
end

local now = redis.call('TIME');
-- second, microSecond, partition, seq
return {tonumber(now[1]), tonumber(now[2]), partition, count + startStep}
